const { ChatModel } = require('../mongoose/models')
module.exports = function (server) {
    const io = require('socket.io').listen(server);
    // io.on('connection',socket => {
    //
    //     console.log('有客户端连接上线','-------------',socket)
    //     //绑定监听，接收客户端发送的消息
    //     socket.on('join-room',()=>{
    //
    //     })
    //     socket.on('sendMsg',function (data) {
    //     console.log('服务器接收到消息',data )
    //     })
    //     socket.emit('receiveMsg',{data:456})
    // })


    io.on('connection',socket => {
        //绑定监听，接收客户端发送的消息
        socket.on('sendMsg',function ({ from,to,content }) {
            const currentUser = io.sockets.sockets[socket.id]
            const chat_id = [from,to].sort().join('_')
            const create_time = Date.now()
            new ChatModel({ from, to, content, chat_id, create_time}).save()
                .then(
                  date => io.emit('receiveMsg',date)
                )
        })
        socket.on('logout',()=>{
            console.log('logout')
            socket.disconnect(true)
            io.emit('receiveLogout',{data:'退出登录成功'})
        })
    })

}



